package com.leyou.goods.controller;

import com.leyou.goods.service.GoodsService;
import com.leyou.goods.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.*;
import java.util.Map;

/**
 * *
 * Created by IntelliJ IDEA.
 * Author: caoLei
 * Date: 2018/11/1
 * Time: 17:52
 * *
 */
@Service
public class GoodsHtmlService {

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private GoodsService goodsService;

    private static final Logger logger = LoggerFactory.getLogger(GoodsHtmlService.class);

    public void createHtml(Long spuId) throws IOException {

        Writer writer = null;

        try {
            //创建上下文对象
            Context  context = new Context();
            //获取页面数据
            Map<String, Object> map = this.goodsService.loadModel(spuId);
            //将数据添加到上下文中
            context.setVariables(map);
            //创建输出流
            File file = new File("D:\\nginx-1.14.0\\html\\item\\" + spuId + ".html");
            writer = new PrintWriter(file);
            //执行页面静态方法
            templateEngine.process("item", context, writer);
        } catch (FileNotFoundException e) {
            logger.error("页面静态化失败",e);
        }finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 新建线程处理页面静态化(优化)
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(()-> {
            try {
                createHtml(spuId);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        /*ThreadUtils.execute(new Runnable() {
            @Override
            public void run() {
                createHtml(spuId);
            }
        });*/
    }

    public void deleteHtml(Long spuId) {
        File file = new File("D:\\nginx-1.14.0\\html\\item\\" + spuId + ".html");
        file.deleteOnExit();

    }
}
